package com.hz.friends.fragment.nearby;

import java.util.ArrayList;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.astuetz.PagerSlidingTabStrip;
import com.avos.avoscloud.AVException;
import com.hz.friends.activity.AddFriendsActivity;
import com.hz.friends.activity.EditUserInfosActivity;
import com.hz.friends.activity.MaintabsActivity;
import com.hz.friends.activity.R;
import com.hz.friends.fragment.BaseFragment;
import com.hz.friends.global.Global;
import com.hz.friends.group.GroupCategorySelectActivtiy;
import com.hz.friends.location.LocationService;
import com.hz.friends.serverrequest.ALCCPEngine.ALGroupType;
import com.hz.friends.serverrequest.ALEngineConfig.ALUserGender;
import com.hz.friends.serverrequest.ALUserEngine;
import com.hz.friends.serverrequest.ALEngineConfig.CallBack;
import com.hz.friends.utils.MLog;

public class NearbyFragment extends BaseFragment implements
		View.OnClickListener {
	private ViewPager mviewpager;
	private PagerSlidingTabStrip tabs;
	private DisplayMetrics dm;
	private int pageindex = 0;

	private FrameLayout layout_toplayout;
	private LinearLayout nearby_top_layout1;
	private LinearLayout nearby_top_layout2;
	private LinearLayout nearby_top_layout3;
	private ImageButton imbtn_bar_left;
	private ImageButton imbtn_bar_right;
	private MyViewPagerAdapter pageradpter;
	private BaseNearbyListView nearroom;
	private BaseNearbyListView nearuser;
	private BaseNearbyListView hotroom;
	private double lat = 0;
	private double lon = 0;
	private LocationReciverBroad mlocationReciverBroad;
	private boolean islocation = false;
//	private Animation baranimatin;
//	private Animation baranimatout;

	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_nearby, null);
	}

	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		init();
		initViews();
		initEvents();
		
		// 生成广播处理
		mlocationReciverBroad = new LocationReciverBroad();
		// 实例化过滤器并设置要过滤的广播
		IntentFilter intentFilter = new IntentFilter(Global.LOCAT_ACTION);
		intentFilter.addAction("INTENT_START_LOCATION");
		// 注册广播
		getActivity().registerReceiver(mlocationReciverBroad, intentFilter);

	}

	
	public void startLocation(){
		if(getActivity() == null)
			return;
		//启动定位
		islocation = true;
		((MaintabsActivity) getActivity()).createWiatDialog("正在定位");
		mhandler.removeMessages(3);
		Intent locationintent = new Intent(getActivity(),
				LocationService.class);
		getActivity().startService(locationintent);
		mhandler.sendEmptyMessageDelayed(3, 1000 * 100);
	}
	
	@Override
	protected void init() {
		dm = getResources().getDisplayMetrics();
//		baranimatin = AnimationUtils.loadAnimation(getActivity(),
//				R.anim.slide_up_in);
//		baranimatout = AnimationUtils.loadAnimation(getActivity(),
//				R.anim.slide_up_out);
//		// baranimatin.setFillBefore(true);
//		baranimatin.setFillAfter(true);
//		baranimatout.setFillAfter(true);
	}

	// 根据nerby当前选项卡有group、user显示
	private void showLabelsLayout() {
		layout_toplayout.removeAllViews();
		if (pageindex == 0 || pageindex == 1) {
			layout_toplayout.addView(nearby_top_layout1);
		} else {
			layout_toplayout.addView(nearby_top_layout2);
		}
	}

	@Override
	protected void initViews() {
		imbtn_bar_left = (ImageButton) findViewById(R.id.imbtn_bar_left);
		imbtn_bar_right = (ImageButton) findViewById(R.id.imbtn_bar_right);
		TextView imbtn_bar_title = (TextView) findViewById(R.id.imbtn_bar_title);
		imbtn_bar_title.setText("Near by");

		mviewpager = (ViewPager) findViewById(R.id.mpager);
		tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);

		layout_toplayout = (FrameLayout) findViewById(R.id.layout_toplayout); // 顶部类别选择
		nearby_top_layout1 = (LinearLayout) LayoutInflater.from(getActivity())
				.inflate(R.layout.nearby_top_layout1, null); // 顶部类别选择
		nearby_top_layout2 = (LinearLayout) LayoutInflater.from(getActivity())
				.inflate(R.layout.nearby_top_layout2, null); // 顶部类别选择
		nearby_top_layout3 = (LinearLayout) LayoutInflater.from(getActivity())
				.inflate(R.layout.nearby_top_layout3, null); // 顶部类别选择
		LinearLayout layout_businesslab = (LinearLayout) nearby_top_layout1
				.findViewById(R.id.layout_businesslab);
		LinearLayout layout_foodlab = (LinearLayout) nearby_top_layout1
				.findViewById(R.id.layout_foodlab);
		LinearLayout layout_newslab = (LinearLayout) nearby_top_layout1
				.findViewById(R.id.layout_newslab);
		LinearLayout layout_chatlab = (LinearLayout) nearby_top_layout1
				.findViewById(R.id.layout_chatlab);
		LinearLayout layout_entertainmentlab = (LinearLayout) nearby_top_layout1
				.findViewById(R.id.layout_entertainmentlab);
		LinearLayout layout_alllab = (LinearLayout) nearby_top_layout1
				.findViewById(R.id.layout_alllab);

		LinearLayout layout_genderfemale = (LinearLayout) nearby_top_layout2
				.findViewById(R.id.layout_genderfemale);
		LinearLayout layout_gendermale = (LinearLayout) nearby_top_layout2
				.findViewById(R.id.layout_gendermale);
		LinearLayout layout_genderall = (LinearLayout) nearby_top_layout2
				.findViewById(R.id.layout_genderall);

		ImageButton btn_addfriend = (ImageButton) nearby_top_layout3
				.findViewById(R.id.btn_addfriends);
		ImageButton btn_creategroup = (ImageButton) nearby_top_layout3
				.findViewById(R.id.btn_creategroup);
		btn_addfriend.setOnClickListener(this);
		btn_creategroup.setOnClickListener(this);

		layout_businesslab.setOnClickListener(this);
		layout_foodlab.setOnClickListener(this);
		layout_chatlab.setOnClickListener(this);
		layout_newslab.setOnClickListener(this);
		layout_alllab.setOnClickListener(this);
		layout_entertainmentlab.setOnClickListener(this);

		layout_genderfemale.setOnClickListener(this);
		layout_gendermale.setOnClickListener(this);
		layout_genderall.setOnClickListener(this);

		List<View> mListViews = new ArrayList<View>();
		// TextView tv1 = new TextView(getActivity());
		// ViewPager.LayoutParams lap = new LayoutParams();
		// lap.width = LayoutParams.FILL_PARENT;
		// lap.height = LayoutParams.FILL_PARENT;
		//
		// tv1.setText("ҳ��1");
		// tv1.setLayoutParams(lap);
		// TextView tv2 = new TextView(getActivity());
		// tv2.setText("ҳ��2");
		// tv2.setLayoutParams(lap);
		// TextView tv3 = new TextView(getActivity());
		// tv3.setText("ҳ��3");
		// tv3.setLayoutParams(lap);
		// tv1.setGravity(Gravity.BOTTOM);
		// tv2.setGravity(Gravity.BOTTOM);
		// tv3.setGravity(Gravity.BOTTOM);
		//
		// mListViews.add(tv1);
		// mListViews.add(tv2);
		// mListViews.add(tv3);

		hotroom = new HotRoomListView(getActivity());
		nearroom = new NearByRoomListView(getActivity());
		nearuser = new NearbyuserListView(getActivity());
		View mhotrootlv = hotroom.getView();
		View mnearbyroomlv = nearroom.getView();
		View mnearbyuserlv = nearuser.getView();
		mListViews.add(mhotrootlv);
		mListViews.add(mnearbyroomlv);
		mListViews.add(mnearbyuserlv);
		pageradpter = new MyViewPagerAdapter(mListViews);
		mviewpager.setAdapter(pageradpter);
		tabs.setViewPager(mviewpager);
		setTabsValue();
	}

	@Override
	public void initDatas() {
        startLocation();		
	}
	@Override
	protected void setViews() {

	}

	@Override
	protected void initEvents() {
		tabs.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int arg0) {
				pageindex = arg0;
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {

			}
		});

		imbtn_bar_left.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				imbtn_bar_right.setImageResource(R.drawable.ic_bar_right1);
				showLabelsLayout();
				if (layout_toplayout.isShown()) {// 分类布局显示
					imbtn_bar_left.setImageResource(R.drawable.ic_bar_left1);
//					layout_toplayout.startAnimation(baranimatout);
					layout_toplayout.setVisibility(View.GONE);
					
				} else {
					imbtn_bar_left
							.setImageResource(R.drawable.btn_bar_leftbtn2);
//					layout_toplayout.startAnimation(baranimatin);
					layout_toplayout.setVisibility(View.VISIBLE);
				}

			}
		});

		imbtn_bar_right.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				imbtn_bar_left.setImageResource(R.drawable.ic_bar_left1);
				layout_toplayout.removeAllViews();
				layout_toplayout.addView(nearby_top_layout3);
				if (layout_toplayout.isShown()) {// 分类布局显示
					imbtn_bar_right.setImageResource(R.drawable.ic_bar_right1);
//					layout_toplayout.startAnimation(baranimatout);
					layout_toplayout.setVisibility(View.GONE);
				} else {
					imbtn_bar_right
							.setImageResource(R.drawable.btn_bar_leftbtn2);
//					layout_toplayout.startAnimation(baranimatin);
					layout_toplayout.setVisibility(View.VISIBLE);
				}
			}
		});
		
		
	}

	// 设置滑动标签
	private void setTabsValue() {
		tabs.setShouldExpand(true);
		tabs.setDividerColor(Color.TRANSPARENT);
		tabs.setUnderlineHeight((int) TypedValue.applyDimension(
				TypedValue.COMPLEX_UNIT_DIP, 1, dm));
		tabs.setIndicatorHeight((int) TypedValue.applyDimension(
				TypedValue.COMPLEX_UNIT_DIP, 4, dm));
		tabs.setTextSize((int) TypedValue.applyDimension(
				TypedValue.COMPLEX_UNIT_SP, 15, dm));
		tabs.setIndicatorColor(Color.parseColor("#45c01a"));
		tabs.setSelectedTextColor(Color.parseColor("#45c01a"));
		tabs.setTabBackground(0);
		tabs.setFadingEdgeLength(20);
	}

	private Handler mhandler = new Handler() {

		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 3:// 处理定位
				showSysToast("定位失败,请尝试重新定位");
				if(getActivity() != null){
					Intent locationintent = new Intent(getActivity(),
							LocationService.class);
					getActivity().stopService(locationintent);
					((MaintabsActivity) getActivity()).cancleWaitDialog();
				}
			
				break;
			default:
				break;
			}

		};
	};

	public class MyViewPagerAdapter extends PagerAdapter {
		private List<View> mListViews;
		private final String[] titles = { "Hot room", "Nearby room",
				"Nearby user" };

		@Override
		public CharSequence getPageTitle(int position) {
			return titles[position];
		}

		public MyViewPagerAdapter(List<View> mListViews) {
			this.mListViews = mListViews;
		}

		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView(mListViews.get(position));
		}

		public Object instantiateItem(ViewGroup container, int position) {
			container.addView(mListViews.get(position), 0);
			return mListViews.get(position);
		}

		public int getCount() {
			return mListViews.size();
		}

		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}
 
		public BaseNearbyListView getItemListView() {
			if (pageindex == 0)
				return hotroom;
			if (pageindex == 1)
				return nearroom;
			if (pageindex == 2)
				return nearuser;
			return hotroom;
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_addfriends://添加好友
			startActivity(AddFriendsActivity.class);
			layout_toplayout.setVisibility(View.GONE);
			imbtn_bar_left.setImageResource(R.drawable.ic_bar_left1);
			imbtn_bar_right.setImageResource(R.drawable.ic_bar_right1);

			break;
		case R.id.btn_creategroup://创建群
			startActivity(GroupCategorySelectActivtiy.class);
			layout_toplayout.setVisibility(View.GONE);
			imbtn_bar_left.setImageResource(R.drawable.ic_bar_left1);
			imbtn_bar_right.setImageResource(R.drawable.ic_bar_right1);
			break;
		case R.id.layout_businesslab://聊天室类别
			selectNearbyCategory(ALGroupType.ALGroupTypeOfBusiness);
			break;
		case R.id.layout_foodlab:
			selectNearbyCategory(ALGroupType.ALGroupTypeOfFood);
			break;
		case R.id.layout_newslab:
			selectNearbyCategory(ALGroupType.ALGroupTypeOfNews);
			break;
		case R.id.layout_chatlab:
			selectNearbyCategory(ALGroupType.ALGroupTypeOfChat);
			break;
		case R.id.layout_entertainmentlab:
			selectNearbyCategory(ALGroupType.ALGroupTypeOfEntertainMent);
			break;
		case R.id.layout_alllab:
			selectNearbyCategory(ALGroupType.ALGroupTypeOfNone);
			break;
		case R.id.layout_genderall://性别类别
			selectUserGender(ALUserGender.ALUserGenderOfUndefine);
			break;
		case R.id.layout_genderfemale:
			selectUserGender(ALUserGender.ALUserGenderOfFemale);
			break;
		case R.id.layout_gendermale:
			selectUserGender(ALUserGender.ALUserGenderOfMale);
			break;
		default:
			break;
		}
	}

	private void selectNearbyCategory(ALGroupType grouptype){
		nearroom.setGrouptype(grouptype);
		hotroom.setGrouptype(grouptype);
		nearroom.setLocation(lat, lon);
		hotroom.setLocation(lat, lon);
		pageradpter.getItemListView().getData();
 
		imbtn_bar_left.setImageResource(R.drawable.ic_bar_left1);
		layout_toplayout.setVisibility(View.GONE);
//		layout_toplayout.startAnimation(baranimatout);

	}
	
	private void selectUserGender(ALUserGender usergender){
		nearuser.setUserGender(usergender);
		pageradpter.getItemListView().getData();
		imbtn_bar_left.setImageResource(R.drawable.ic_bar_left1);
		layout_toplayout.setVisibility(View.GONE);
//		layout_toplayout.startAnimation(baranimatout);


	}

	class LocationReciverBroad extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			MLog.i(TAG, " nearby fragment onReciverBrocasd"+intent.getAction());
			if(Global.LOCAT_ACTION == intent.getAction()){
				double lat = intent.getDoubleExtra("lat", 0);
				double lon = intent.getDoubleExtra("lon", 0);
				String address = intent.getStringExtra("address");
				((MaintabsActivity) getActivity()).cancleWaitDialog();
				if ("not_open_set".equals(address)) {
					showSysToast("请打开Gps定位");
					Intent locationintent = new Intent(getActivity(),
							LocationService.class);
					getActivity().stopService(locationintent);
					return;
				}

				if (lat > 0 && lon > 0 ) {
//					showSysToast("定位成功");
					if(!islocation)
						return;
					islocation = false;
					Intent locationintent = new Intent(getActivity(),
							LocationService.class);
					getActivity().stopService(locationintent);
					NearbyFragment.this.lat = lat;
					NearbyFragment.this.lon = lon;
					nearroom.setLocation(lat, lon);
					nearuser.setLocation(lat, lon);
					nearroom.getData();
					nearuser.getData();

					// 上传经纬度
					ALUserEngine.defauleEngine().updateLocation(lat, lon, address,
							new CallBack() {

								@Override
								public void done(Object object,
										AVException avexception) {

								}
							});

				} else {
					if(!islocation)
						return;
					showSysToast("定位失败,请尝试重新定位");
					Intent locationintent = new Intent(getActivity(),
							LocationService.class);
					getActivity().stopService(locationintent);
				}
			}
			
			if("INTENT_START_LOCATION".equals(intent.getAction())){//开始定位
				startLocation();
			}


		}

	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		Intent locationintent = new Intent(getActivity(), LocationService.class);
		getActivity().stopService(locationintent);
		getActivity().unregisterReceiver(mlocationReciverBroad);
	}


}
